package org.mango.base;

import com.alibaba.fastjson.JSONObject;
import org.mango.util.KeyUtil;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * Created by meigang on 17/9/9.
 */
public class BaseAction {

    @Resource
    HttpServletRequest req;

    protected String getCtx(){
        return req.getContextPath();
    }

    protected void setSessionAttr(String key,Object value){
        req.getSession().setAttribute(key,value);
    }

    protected Object getSessionAttr(String key){
        return req.getSession().getAttribute(key);
    }

    protected void setAttr(String key,Object value){
        req.setAttribute(key,value);
    }

    protected Object getAttr(String key){
        return req.getAttribute(key);
    }

    protected String getJarReactStr(ResourcePatternResolver resolver, String m, String module_path) throws IOException {
        InputStream is = resolver.getResource(module_path+m).getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        byte[] buffer = new byte[bis.available()];
        bis.read(buffer);
        String packageStr = new String(buffer,"utf-8");
        bis.close();
        is.close();
        return packageStr;
    }

    protected String ajaxJson(int state){
        JSONObject json = new JSONObject();
        json.put("state",state);
        return json.toJSONString();
    }

    protected String ajaxJson(int state,Object msg){
        JSONObject json = new JSONObject();
        json.put("state",state);
        json.put("msg",msg);
        return json.toJSONString();
    }

    protected String ajaxJson(int state,String msg){
        JSONObject json = new JSONObject();
        json.put("state",state);
        json.put("msg",msg);
        return json.toJSONString();
    }

    protected JSONObject getParamJson(){
        JSONObject json = new JSONObject();
        Map<String, String[]> map = this.req.getParameterMap();
        for(String key : map.keySet()){
            json.put(key,map.get(key).length==1 ? map.get(key)[0] : map.get(key));
        }
        return json;
    }

    public void renderJson(HttpServletResponse res, String s) throws IOException {
        res.getOutputStream().write(s.getBytes(Charset.forName("utf-8")));
        res.getOutputStream().close();
    }
}
